#!/usr/bin/env python
#coding: utf-8
'''
Created on 2017年4月17日

@author: Administrator
'''
import datetime

from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone

from common.models.abstract import StateModel, TimeModel
from message import settings


class MessageManager(models.Manager):
    
    def user_get_receive(self, user):
        """ 用户收件箱 """
        return self.filter(state=0, recv_user=user).exclude(category=0).order_by('readed', '-create_time')
    
    def create_message(self, recv_user, content, send_user=None):
        '''
        创建消息
        '''
        if send_user == None:
            try:
                send_user = User.objects.get(username=settings.SYSTEM_MESSAGE_USER)
            except User.DoesNotExist:
                return
        msg = Message(send_user=send_user,
                      recv_user=recv_user,
                      content=content)
        msg.save()
        
    def send_message(self, category, send_user, recv_user, content):
        '''发消息'''
        msg = Message.objects.create(category=category, send_user=send_user, recv_user=recv_user, content=content)
        return msg

    def send_system_message(self, recv_user, content):
        send_user = User.objects.get(username=settings.SYSTEM_MESSAGE_USER)
        msg = self.send_message(settings.MessageCategoryEnum.SYSTEM, send_user, recv_user, content)
        return msg
    
    def get_message(self, category, recv_user_id):
        return self.filter(state=0, recv_user_id=recv_user_id, category=category).order_by('readed', '-create_time')
    
    def get_unreaded_message(self, category, recv_user_id):
        return self.get_message(category, recv_user_id).filter(readed=False)
    
    def get_readed_message(self, category, recv_user_id):
        return self.get_message(category, recv_user_id).filter(readed=True)
    
    def get_own_message(self, category, recv_user_id, send_user_id):
        return self.filter(recv_user_id=recv_user_id, category=category, send_user_id=send_user_id).order_by('readed', '-create_time')
      
    def get_own_unreaded_message(self, category, recv_user_id, send_user_id):
        return self.filter(state=0, recv_user_id=recv_user_id, category=category, send_user_id=send_user_id, readed=False).order_by('readed', '-create_time')

    def get_post_message(self, category, send_user_id):
        return self.filter(state=0, send_user_id=send_user_id, category=category).order_by('readed', '-create_time')
    

class Message(StateModel, TimeModel):
    """ 消息系统 """
    category = models.PositiveSmallIntegerField(default=settings.MessageCategoryEnum.NORMAL, choices=settings.MESSAGE_CATEGORY_CHOICES, verbose_name=u'消息类型')
    send_user = models.ForeignKey(User, related_name='send_message', verbose_name=u'发送者')
    recv_user = models.ForeignKey(User, related_name='recv_message', verbose_name=u'接收者')
    content = models.TextField(verbose_name=u'消息内容')
    readed = models.BooleanField(default=False, verbose_name=u'已读')
    
    objects = MessageManager()

    class Meta:
        app_label = 'message'
        verbose_name = u'消息'
        verbose_name_plural = u'消息'

    def __unicode__(self):
        return u'[%s]:[%s] %s' % (self.send_user, self.recv_user, self.content)
    

class EmailMessage(StateModel, TimeModel):
    '''
    邮件消息
    '''
    recv_user = models.ForeignKey(User, blank=True, null=True, verbose_name=u'接收用户')
    email = models.EmailField(verbose_name=u'收件人Email')
    subject = models.CharField(default=u'', max_length=64, verbose_name=u'邮件主题')
    content = models.TextField(verbose_name=u'邮件内容')
    type = models.SmallIntegerField(default=0,choices=settings.EMAIL_TYPE_CHOICES,db_index=True, verbose_name=u'邮件类型')
    is_pushed = models.BooleanField(default=False, verbose_name=u'是否已经发送')

    class Meta:
        app_label = 'message'
        verbose_name = u'邮件消息'
        verbose_name_plural = u'邮件消息'

    def __unicode__(self):
        return u'To:[%s] %s' % (self.email, self.content)

class MobileMessage(StateModel, TimeModel):
    '''
            手机短信
    '''
    recv_user = models.ForeignKey(User, blank=True, null=True, verbose_name=u'接收者')
    mobile = models.CharField(max_length=24, verbose_name=u'手机号码')
    content = models.TextField(verbose_name=u'消息内容')
    type = models.SmallIntegerField(default=0,choices=settings.SMS_TYPE_CHOICES,db_index=True, verbose_name=u'短信类型')
    is_pushed = models.BooleanField(default=False, verbose_name=u'是否已经发送')

    class Meta:
        app_label = 'message'
        verbose_name = u'手机短信'
        verbose_name_plural = u'手机短信'

    def __unicode__(self):
        return u'To:[%s] %s' % (self.mobile, self.content)


class ValidateMessageManager(models.Manager):
    
    def get_latest_sended_message(self, to_who):
        lst = self.filter(sendto=to_who).extra(order_by=['-create_time'])[0:1]
        return lst[0] if lst else None

    def get_sended_count_by_ip(self, ip):
        today = timezone.now()
        yesterday = today - timezone.timedelta(hours=6)
        return self.filter(ip=ip, create_time__range=(yesterday, today)).count()

    def get_sended_count_by_sendto(self, sendto):
        today = timezone.now()
        yesterday = today - timezone.timedelta(hours=6)
        return self.filter(sendto=sendto, create_time__range=(yesterday, today)).count()

    def validate_message(self, to_who, validatecode, ip):
        vm = self.filter(state=0, sendto=to_who, validatecode=validatecode,
                    is_pushed=True, ip=ip).extra(order_by=['-create_time'])[0:1]
        if vm:
            vm = vm[0]
            if timezone.now() > (vm.create_time + timezone.timedelta(minutes=5)):
                return False, 'VERIFYCODE_ERR'
            vm.useat = timezone.now()
            vm.save()
            return True, 'SUCC'
        else:
            return False, 'VERIFYCODE_ERR'
    
    def validate_mobile_code(self, mobile, verifycode, ip, active_time=5 * 60):
        '''
        校验短信验证码
        mobile - 手机号码
        verifycode - 验证码
        ip - ip地址
        active_time - 需要校验的验证码有效时间，单位为秒
        return  True/False
        '''
        vms = self.only('id', 'create_time', 'useat').filter(category=0, state=0, sendto=mobile, validatecode=verifycode,
                    is_pushed=True, ip=ip).extra(order_by=['-create_time'])[0:1]
        if vms:
            vm = vms[0]
            now_time = datetime.datetime.now()
            if now_time > (vm.create_time + datetime.timedelta(seconds=active_time)):
                vm.useat = now_time
                vm.save()
                return True
        return False

class ValidateMessage(StateModel, TimeModel):
    '''验证消息'''
    category = models.PositiveSmallIntegerField(default=0, choices=settings.VALIDATE_CATEGORY, verbose_name=u'验证类型')
    sendto = models.CharField(max_length=100, verbose_name=u'发送目标')
    validatecode = models.CharField(default='', max_length=6, verbose_name=u'验证码')
    is_pushed = models.BooleanField(default=False, verbose_name=u'是否已经发送')
    ip = models.IPAddressField(default='', verbose_name=u'ip地址')
    useat = models.DateTimeField(blank=True, null=True, verbose_name=u'使用时间')
    
    objects = ValidateMessageManager()
    
    class Meta:
        app_label = 'message'
        verbose_name = u'验证消息'
        verbose_name_plural = u'验证消息'

    def __unicode__(self):
        return u'To:[%s] %s' % (self.sendto, self.validatecode)
    
    
